#!/bin/sh

DIALOG="/opt/QtDialog/bin/QtDialog"
TITLE="Bluetooth keyboard manager"

if ! dpkg -l bluez-test >/dev/null ; then
	$DIALOG --title "$TITLE" --msgbox "<center>Please install <b>bluez-test</b> package!</center>"
	exit 1
fi

BTADAPTER=`dbus-send --system --dest=org.bluez --print-reply / org.bluez.Manager.DefaultAdapter | tail -1 | sed 's/^.*"\(.*\)".*$/\1/'`

ENT=""

for d in `dbus-send --system --dest=org.bluez --print-reply $BTADAPTER org.bluez.Adapter.ListDevices | awk '{ gsub(/"/,""); if ( $2 == "path" ) print $3 }'`; do

get_name() {
	local p
	local c
	local v
	dbus-send --system --dest=org.bluez --print-reply $d org.bluez.Device.GetProperties | while read p; do
		case "$c" in
		Name)
			v=`echo $p | awk '{ gsub(/^.* "|"/,""); print $0 }'`
			echo "<b>$v</b><br />`echo $d | awk '{ gsub(/^.*dev_/,""); gsub(/_/,":"); print $0}'`"
			return 0
			;;
		*)
			c=""
			;;
		esac
		c=`echo $p | awk '{ gsub(/"/,""); if ( $2 == "Name") print $2 }'`
	done
}

	e=`get_name`
	echo ">> $e"
	ENT="$e\n$ENT"
done

DEV=`echo -e "$ENT" | $DIALOG --title "$TITLE" --listbox "Select keyboard device:"`

if  [ "$?" != "0" -o "$DEV" == "" ]; then
	echo "cancelled"
	exit 0
else
	echo ">> $DEV"
	$DIALOG --title "$TITLE" --yesno "<center>Connecting to selected device?<br />$DEV</center>"
	if [ "$?" == "0" ]; then
		BTADDR=`echo $DEV | awk '{ gsub(/^.*>/,""); print $0 }'`
		echo "-- $BTADDR"
		hidd --connect $BTADDR
		if [ "$?" == "0" ]; then
			MSG="<center>Keyboard successfully connected to phone!</center>"
		else
			MSG="<center>Connection failed! Check keyboard pairing, turn keyboard on or press keyboard link button and try again!</center>"
		fi
		$DIALOG --title "$TITLE" --msgbox "$MSG"
	fi
fi
